<script setup lang="ts">
import { freeType, frequencyType } from "@/config/dictionary";
import { zoonType } from "../components/config";
import { deepClone } from "@/utils";
import PrizePool from "./PrizePool.vue";

const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
  },
});

const emits = defineEmits(["change", "update:modelValue"]),
  activityBaseInfo: any = inject("activityBaseInfo", {});

const form = ref<any>({
  partType: 0,
  freeType: 4,
  partTotalLimit: 0,
  lotteryTotalLimit: 0,
  lotteryLimitType: 0,
}),
  prizeAreas = ref<Array<any>>([]),
  currencyList = inject("currencyList", []);

const formRef = ref(),
  poolRef = ref();

const rules = {
  freeNum: [{ required: true, message: "请输入免费次数", trigger: "blur" }],
  integralId: [
    { required: true, message: "请选择积分类型", trigger: "change" },
  ],
  integralNum: [{ required: true, message: "请输入积分数量", trigger: "blur" }],
  price: [{ required: true, message: "请输入金额", trigger: "blur" }],
  partTotalNum: [
    { required: true, message: "请输入参与总次数", trigger: "blur" },
  ],
  lotteryTotalNum: [
    { required: true, message: "请输入中奖总次数", trigger: "blur" },
  ],
};

const prizePoolType = computed(() => {
  return form.value.subType ? zoonType[form.value.subType].prizePool || [] : [];
});

const createPool = (base: any) => {
  let pool: any = {};

  pool = {
    defaulted: base.defaulted,
    type: base.type,
    subType: base.subType,
    pageFlag: form.value.pageFlag,
    name: `${base.defalut ? "默认" : ""}${base.name}`,
    uid: `${form.value.pageFlag}-pool-${prizeAreas.value.length}`,
    prizeInfos: [],
    viewExpression: "",
    viewOriginal:
      base.viewOriginal && typeof base.viewOriginal === "string"
        ? JSON.parse(base.viewOriginal)
        : base.viewOriginal,
  };
  // 抽奖奖池默认有谢谢惠顾
  if (base.type == 1) {
    pool.prizeInfos.push({
      name: "谢谢参与",
      thumbnailUrl:
        "https://static.lianhaikeji.com/unimall/B3EA587641F749408E310DE83DC956B7.png",
      onlineStatus: 1,
      defaulted: 1,
      prizeType: 0,
      probability: 1,
      uid: `${pool.uid}-prize-1`,
    });
  }

  return pool;
};

const limitsDisabled = computed(() => {
  return form.value.hasTicket == 1 && activityBaseInfo.value.status == 2;
});

const stopWatch = watch(
  () => props.modelValue,
  (val) => {
    nextTick(() => {
      stopWatch();
      formatData(val);
    });
  },
  {
    immediate: true,
  }
);

const formatData = (val: any) => {
  form.value = Object.assign({}, form.value, {
    ...val.pageArea,
    price: val.pageArea.price
      ? Number(((val.pageArea.price || 0) / 100).toFixed(2))
      : val.pageArea.price,
    partLimit:
      val.pageArea.partLimit && typeof val.pageArea.partLimit === "string"
        ? JSON.parse(val.pageArea.partLimit)
        : [{ type: 1, limitNum: 1 }],
    lotteryLimit:
      val.pageArea.lotteryLimit && typeof val.pageArea.lotteryLimit === "string"
        ? JSON.parse(val.pageArea.lotteryLimit)
        : [{ type: 1, limitNum: 1 }],
    lotteryLimitType: val.pageArea.lotteryLimit ? 1 : 0,
  });
  prizeAreas.value = val.prizeAreas || [];
  // 新建活动初始化奖池
  if (prizeAreas.value.length == 0) {
    for (let i = 0; i < prizePoolType.value.length; i++) {
      prizeAreas.value.push(
        createPool({
          ...prizePoolType.value[i],
        })
      );
    }
  }
  updateData();
};

const updateData = () => {
  emits("update:modelValue", {
    pageArea: form.value,
    prizeAreas: prizeAreas.value,
  });
  emits("change");
};

const submit = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate(async (valid: any, invalidFields: any) => {
      if (valid) {
        let detail: any = deepClone(form.value);
        // 每人中奖限制
        if (detail.lotteryLimitType == 0) {
          detail.lotteryLimit = "";
        } else if (detail.lotteryLimit)
          detail.lotteryLimit = JSON.stringify(detail.lotteryLimit);

        if (detail.price)
          detail.price = parseInt((Number(detail.price) * 100).toFixed(2).slice(0, -3));
        // 每人参与限制
        if (detail.partLimit)
          detail.partLimit = JSON.stringify(detail.partLimit);
        // 检查奖池
        try {
          await poolRef.value.check(
            detail.lotteryLimitType === 1 || detail.lotteryTotalLimit === 1,
            true
          );
        } catch (e) {
          reject(e);
        }

        resolve({
          pageArea: detail,
          prizeAreas: prizeAreas.value,
        });
      } else {
        formRef.value.scrollToField(Object.keys(invalidFields)[0]);
        reject(`请检查${form.value.name}`);
      }
    });
  });
};

defineExpose({ submit, refresh: formatData });
</script>
<template>
  <el-form ref="formRef" :model="form" :rules="rules" :disabled="activityReadonly" label-width="auto">
    <h3 class="collpase-title">参与限制</h3>
    <el-form-item label="参与消耗：">
      <el-radio-group v-model="form.partType" :disabled="limitsDisabled">
        <el-radio :label="0">不消耗</el-radio>
        <el-radio :label="1">积分</el-radio>
        <el-radio :label="2">现金</el-radio>
        <el-radio :label="3">现金+积分</el-radio>
      </el-radio-group>
    </el-form-item>
    <!-- 现金 -->
    <template v-if="form.partType == 2 || form.partType == 3">
      <el-form-item prop="price">
        <EasyNumberInput v-model="form.price" :min="0.01" :max="9999" unit="元" :disabled="limitsDisabled" />
      </el-form-item>
    </template>
    <!-- 积分 -->
    <template v-if="form.partType == 1 || form.partType == 3">
      <el-form-item>
        <el-form-item label-width="0px" prop="integralNum">
          <EasyNumberInput v-model="form.integralNum" :min="1" :max="9999" unit="个" :precision="0"
            :disabled="limitsDisabled" />
        </el-form-item>
        <el-form-item label-width="10px" prop="integralId">
          <el-select v-model="form.integralId" placeholder="请选择" style="width: 100px" :disabled="limitsDisabled">
            <el-option v-for="(item, key) in currencyList" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form-item>
    </template>
    <el-form-item label="免费次数：">
      每人&nbsp;&nbsp;
      <el-form-item label-width="10px" prop="freeNum">
        <EasyNumberInput v-model="form.freeNum" :min="0" :max="9999" unit="次" :precision="0" :disabled="limitsDisabled" />
      </el-form-item>&nbsp;&nbsp;
      <el-select v-model="form.freeType" placeholder="请选择" style="width: 100px">
        <el-option v-for="(item, key) in freeType" :label="item" :value="Number(key)" />
      </el-select>
    </el-form-item>
    <el-form-item label="参与总次数：">
      <el-radio-group v-model="form.partTotalLimit" :disabled="limitsDisabled">
        <el-radio :label="0">不限</el-radio>
        <el-radio :label="1">限制</el-radio>
      </el-radio-group>
      <template v-if="form.partTotalLimit == 1">
        <el-form-item label-width="10px" prop="partTotalNum">
          <EasyNumberInput v-model="form.partTotalNum" :min="1" :max="9999" :precision="0" unit="次"
            :disabled="limitsDisabled" />
        </el-form-item>
      </template>
    </el-form-item>
    <el-form-item label="参与次数：">
      <div class="flex-contain" v-for="(limit, index) in form.partLimit">
        每人&nbsp;&nbsp;
        <el-select v-model="limit.type" placeholder="请选择" style="width: 100px" :disabled="limitsDisabled">
          <el-option v-for="(item, key) in frequencyType" :label="item" :value="Number(key)" /> </el-select>&nbsp;&nbsp;
        最多
        <el-form-item label-width="10px" :prop="`partLimit.${index}.limitNum`" :rules="[
          { required: true, message: '请填写限制次数', trigger: 'blur' },
        ]">
          <EasyNumberInput v-model="limit.limitNum" :min="1" :max="9999" unit="次" :precision="0"
            :disabled="limitsDisabled"></EasyNumberInput>
        </el-form-item>
      </div>
    </el-form-item>
    <!-- 中奖限制 -->
    <h3 class="collpase-title">中奖限制</h3>
    <el-form-item label="中奖总次数：" prop="lotteryTotalLimit">
      <el-radio-group v-model="form.lotteryTotalLimit">
        <el-radio :label="0">不限</el-radio>
        <el-radio :label="1">限制</el-radio>
      </el-radio-group>
      <template v-if="form.lotteryTotalLimit == 1">
        <el-form-item label-width="10px" prop="lotteryTotalNum">
          <EasyNumberInput v-model="form.lotteryTotalNum" :min="1" :max="9999" :precision="0" unit="次" />
        </el-form-item>
      </template>
    </el-form-item>
    <el-form-item label="中奖次数：">
      <el-radio-group v-model="form.lotteryLimitType">
        <el-radio :label="0">不限</el-radio>
        <el-radio :label="1">限制</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item v-if="form.lotteryLimitType == 1">
      <div class="flex-contain" v-for="(limit, index) in form.lotteryLimit">
        每人&nbsp;&nbsp;
        <el-select v-model="limit.type" placeholder="请选择" style="width: 100px">
          <el-option v-for="(item, key) in frequencyType" :label="item" :value="Number(key)" /> </el-select>&nbsp;&nbsp;
        最多
        <el-form-item label-width="10px" :prop="`lotteryLimit.${index}.limitNum`" :rules="[
          { required: true, message: '请填写限制次数', trigger: 'blur' },
        ]">
          <EasyNumberInput v-model="limit.limitNum" :min="1" :max="9999" unit="次" :precision="0"></EasyNumberInput>
        </el-form-item>
      </div>
    </el-form-item>
  </el-form>
  <PrizePool ref="poolRef" v-model="prizeAreas" :poolType="[1]" :poolBaseInfo="prizePoolType" :pageFlag="form.pageFlag"
    @change="updateData"></PrizePool>
</template>
<style lang="scss" scoped>
.collpase-title {
  position: relative;
  padding-left: 10px;
  font-size: 16px;
  margin-bottom: 10px;

  &::before {
    content: "";
    display: block;
    width: 3px;
    height: 16px;
    border-radius: 2px;
    background-color: var(--el-color-primary);
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
  }

  span {
    font-size: 13px;
    color: #909399;
    margin-left: 10px;
    font-weight: normal;
  }
}

.flex-contain {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}
</style>
